﻿#region Using
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
#endregion Using

namespace LloydGame
{
    public class MotionBlurImageProcessor : ImageProcessor
    {
        #region Class Fields
        protected RenderTarget2D m_blurTarget;

        protected Matrix m_viewProjPrev;
        #endregion Class Fields

        // constructor
        public MotionBlurImageProcessor(Game p_game, int p_imageWidth, int p_imageHeight)
            : base(p_game, p_imageWidth, p_imageHeight)
        {
            m_blurTarget = new RenderTarget2D(
                p_game.GraphicsDevice,
                p_imageWidth,
                p_imageHeight,
                1,
                p_game.GraphicsDevice.DisplayMode.Format);

            m_depthStencil = new DepthStencilBuffer(
                m_blurTarget.GraphicsDevice,
                m_blurTarget.Width,
                m_blurTarget.Height,
                m_blurTarget.GraphicsDevice.DepthStencilBuffer.Format,
                m_blurTarget.MultiSampleType,
                m_blurTarget.MultiSampleQuality);

            m_effect = Game.Content.Load<Effect>("Effects\\MotionBlur");

            m_viewProjPrev = new Matrix();
        }

        // perform motion blur
        public Texture2D process(Texture2D p_colorTex, Texture2D p_depthTex)
        {
            m_effect.CurrentTechnique = m_effect.Techniques["Blur"];

            setCornerFrustum();

            m_effect.Parameters["vpPrev"].SetValue(m_viewProjPrev);
            m_effect.Parameters["vInv"].SetValue(Matrix.Invert(((Game1)Game).camera.view));
            
            m_effect.Parameters["colorTex"].SetValue(p_colorTex);
            m_effect.Parameters["depthTex"].SetValue(p_depthTex);

            Game.GraphicsDevice.SetRenderTarget(0, m_blurTarget);
            
            processPass(0);

            Game.GraphicsDevice.SetRenderTarget(0, null);

            m_viewProjPrev = ((Game1)Game).camera.viewProj;

            return m_blurTarget.GetTexture();
        }
    }
}
